﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerController : MonoBehaviour {

    GameObject farmer;
    List<GameObject> followerList;

    Object cowSource;

	// Use this for initialization
	void Start () {
        farmer = GameObject.FindGameObjectWithTag("farmer");
        followerList = new List<GameObject>();

        cowSource = Resources.Load("Prefabs/cow");
	}
	
	// Update is called once per frame
	void Update () {
        float deltaTransition = 30*Time.deltaTime;
        // update farmer
        farmer.transform.Translate(new Vector3(0, 0, deltaTransition), Space.Self);
        // update follower
        if (followerList.Count > 0) {
            for (int i = 0; i < followerList.Count; i++) {
                // update rotasi
                if (i == 0) 
                    followerList[i].transform.LookAt(farmer.transform);
                else
                    followerList[i].transform.LookAt(followerList[i-1].transform);
                // update position
                followerList[i].transform.Translate(new Vector3(0, 0, deltaTransition), Space.Self);
            }
        }

        // handle input
        HandleInput();
	}

    void HandleInput() {
        float deltaRotation = 90*Time.deltaTime;

        if (Input.GetKey(KeyCode.LeftArrow)) {
            farmer.transform.Rotate(Vector3.up, -deltaRotation);
        }
        else if (Input.GetKey(KeyCode.RightArrow)) {
            farmer.transform.Rotate(Vector3.up, deltaRotation);            
        }

        if (Input.GetKeyDown(KeyCode.A)) AddCow();
    }

    void AddCow() {
        GameObject newCow = (GameObject)Instantiate(cowSource);
        float gap = 10; // jarak antara character

        // kalau belum ada follower maka ikutin posisi farmer
        if (followerList.Count == 0)
        {
            newCow.transform.position = farmer.transform.position;
            newCow.transform.rotation = farmer.transform.rotation;
            newCow.transform.Translate(new Vector3(0, 0, -gap),Space.Self);
        }
        else // ikutin posisi follower paling ujung
        { 
            newCow.transform.position = followerList[followerList.Count - 1].transform.position;            
            newCow.transform.rotation = followerList[followerList.Count - 1].transform.rotation;
            newCow.transform.Translate(new Vector3(0, 0, -gap),Space.Self);
        }

        followerList.Add(newCow);
    }
}
